#include "edit_base.h"

EditBaseWidget::EditBaseWidget(QString FilePath, QWidget *parent):QWidget(parent)
{
    update_file_info(FilePath);

}

void EditBaseWidget::load_window()
{
    text_edit = nullptr;
    load_file_content();
    init_base_member_val();
    init_extra_member_val();
    InitUiStyle();
}

const QString& EditBaseWidget::get_filename()
{
    return file_name;
}

const QString &EditBaseWidget::get_full_filename()
{
    return full_filename;
}



void EditBaseWidget::load_file_content()
{
    QFile file(full_filename);
    file.open(QIODevice::ReadOnly);
    QByteArray t =file.readAll();
    file_content = t;
    file.close();
}

void EditBaseWidget::InitUiStyle()
{
    text_edit->setPlainText(file_content);
    resize_editer(width(), height());

}

void EditBaseWidget::init_base_member_val()
{
    text_edit = new MPlainTextEditer();
    text_edit->setParent(this);
    connect(text_edit, SIGNAL(textChanged()), this, SLOT(file_edited()));
}

bool EditBaseWidget::is_file_changed()
{
    return file_new_content.compare(file_content);
}



void EditBaseWidget::save_file()
{
    QFile file(full_filename);
    bool is_success = file.open(QIODevice::WriteOnly);
    if(is_success){
        file.write(file_new_content.toStdString().c_str());
        file_content = file_new_content;
    }
    file.close();
}

void EditBaseWidget::update_file_info(QString FilePath)
{
    full_filename = FilePath;
    file_name = get_file_name_use_path(FilePath);
}

void EditBaseWidget::file_edited()
{
    file_new_content = text_edit->toPlainText();
}

void EditBaseWidget::resize_editer(int w, int h)
{
    this->resize(w, h);
    if (text_edit){
        text_edit->resize(w,h);
    }
}

void EditBaseWidget::init_extra_member_val()
{
    return;
}


